<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-3-13
 * Time: 上午9:08
 */

namespace api\modules\chedai\controllers;


use api\modules\chedai\Config;
use api\modules\chedai\tools\ApiTools;
use common\components\tools\Model;
use common\components\tools\Tools;
use common\models\AliCarinfoGetLog;
use common\models\Che300CarModel;
use common\models\Che300CmVinBind;
use common\models\credit_app\Member;
use common\models\credit_app\Order;
use common\models\credit_app\OrderCar;
use common\models\credit_public\SlCarModel;
use common\models\credit_public\SlCarModelDycw;
use common\models\credit_public\SlCarModelQczj;
use common\models\credit_public\SlCarModelSyc;
use common\models\credit_public\SlCarSeries;
use common\models\credit_public\SlCarSeriesDycw;
use common\models\credit_public\SlCarSeriesQczj;
use common\models\credit_public\SlCarSeriesSyc;
use wodrow\yii\rest\ApiException;
use wodrow\yii\rest\Controller;
use yii\base\ErrorException;
use yii\db\Exception;
use yii\httpclient\Client;

class CarController extends Controller
{
    /**
     * 修改车辆信息
     * @desc post 一般ot开头
     * @param int $order_id 客户订单号
     * @param int $o_bank_id 银行号，有的话需要计算，无不需要
     * @throws
     */
    public function actionSave($order_id, $o_bank_id = null)
    {
        $order = $this->_getOrder($order_id);
        if (!$order){
            throw new ErrorException("没有找到客户订单!");
        }
        $car = $order->car;
        if (!$car){
            throw new ErrorException("没有找到车辆!");
        }
        $post = \Yii::$app->request->post();
        $post['oid'] = $post['order_id'];
        if (isset($post['ot_calculated'])){
            unset($post['ot_calculated']);
        }
//        var_dump($post);exit;
        if ($o_bank_id){
            $client = new Client();
            $response = $client->post(Config::CHEDAI_URL."/public/bank/option/loanrate")->setData($post)->send();
            Tools::log($response->content);
            $x = json_decode($response->content, true, 512);
            if (!isset($x['errcode'])||$x['errcode']!=0){
                throw new ErrorException("计算错误:".$x['msg']);
            }
            $y = $x['data'];
            if (isset($y['car_info']))unset($y['car_info']);
            $y['bank_rate'] = $car->ot_bankrt_rate/100;
            $post['ot_calculated'] = json_encode($y);
        }
        $car->load(ApiTools::setSerializeApiField($post, OrderCar::$serialize_fields), '');
        $x = $car->save(false);
        if (!$x){
            throw new Exception(Tools::makeModelGetErrorsToStringAndGetIt($car));
        }
        $o['car'] = ApiTools::showSerializeApiField($car->toArray(), OrderCar::$serialize_fields);
        $o['order'] = $order->toArray();
//        Tools::log($o);
        return $o;
    }

    /**
     * @param $order_id
     * @return null|static|Order
     */
    private function _getOrder($order_id)
    {
        $order = \common\models\credit_app\Order::findActiveOneById($order_id);
        if ($order){
            if (!in_array($order->o_status, Order::getCanOptStatus())){
                throw new ErrorException("当前状态不允许操作");
            }
        }
        return $order;
    }

    /**
     * 获取所有车系
     * @param string $source 源
     * @return array
     * @return array all_series 所有车系
     */
    public function actionGetAllCarSeries($source = 'che300', $is_shangyong_or_chengyong = '')
    {
        switch ($source){
            case 'che300':
                $series = SlCarSeries::find()->asArray()->all();
                $series_count = SlCarSeries::find()->count();
                break;
            case 'dycw':
                $series = SlCarSeriesDycw::find()->asArray()->all();
                $series_count = SlCarSeriesDycw::find()->count();
                break;
            case 'qczj':
                $series = SlCarSeriesQczj::find()->asArray()->all();
                $series_count = SlCarSeriesQczj::find()->count();
                break;
            default:
                throw new ApiException(201903311810, "没有找到源");
                break;
        }
        $r = [
            'all_series' => $series,
            'series_count' => $series_count,
        ];
        return $r;
    }

    /**
     * 根据车系id获取所有车型
     * @param string $series_id 车系id
     * @param string $source 源
     * @return array
     * @return array all_series 所有车系
     */
    public function actionGetAllCarModelsBySeriesId($series_id, $source = 'che300')
    {
        switch ($source){
            case 'che300':
                $models = SlCarModel::find()->where(['series_id' => $series_id])->asArray()->all();
                foreach ($models as $k => $v){
                    if (!is_numeric($v['seat_number'])){
                        $models[$k]['seat_number'] = 0;
                    }
                }
                $models_count = SlCarModel::find()->where(['series_id' => $series_id])->count();
                break;
            case 'dycw':
                $models = SlCarModelDycw::find()->where(['series_id' => $series_id])->asArray()->all();
                foreach ($models as $k => $v){
                    if (!is_numeric($v['seat_number'])){
                        $models[$k]['seat_number'] = 0;
                    }
                }
                $models_count = SlCarModelDycw::find()->where(['series_id' => $series_id])->count();
                break;
            case 'qczj':
                $models = SlCarModelQczj::find()->where(['series_id' => $series_id])->asArray()->all();
                foreach ($models as $k => $v){
                    if (!is_numeric($v['seat_number'])){
                        $models[$k]['seat_number'] = 0;
                    }
                }
                $models_count = SlCarModelQczj::find()->where(['series_id' => $series_id])->count();
                break;
            default:
                throw new ApiException(201903311811, "没有找到源");
                break;
        }
        $r = [
            'all_models' => $models,
            'models_count' => $models_count,
        ];
        return $r;
    }

    /**
     * @param $uid
     * @param $bank_id
     * @param string $car_use_type
     * @param string $t
     * @return string
     * @throws
     */
    private function _getCarSMClassName($uid, $bank_id, $car_use_type = 'cyc', $t)
    {
        if ($car_use_type == 'syc'){
            $x = $this->actionCheckSyc($uid);
            if (!$x['result']){
                throw new ApiException(201906191417, $x['message']);
            }
        }
        if ($car_use_type == 'syc'){
            $s = SlCarSeriesSyc::class;
            $m = SlCarModelSyc::class;
        }else{
            if ($bank_id == 11){
                $s = SlCarSeries::class;
                $m = SlCarModel::class;
            }elseif ($bank_id == 17){ // 中国工商银行股份有限公司南京江宁支行
                $s = SlCarSeries::class;
                $m = SlCarModel::class;
            }elseif ($bank_id == 18){ // 中国工商银行股份有限公司西安北大街支行
                $s = SlCarSeries::class;
                $m = SlCarModel::class;
            }else{
                $s = SlCarSeries::class;
                $m = SlCarModel::class;
            }
        }
        if ($t == 's'){
            return $s;
        }
        if ($t == 'm'){
            return $m;
        }
    }

    /**
     * 获取所有车系1
     * @param string $source 源
     * @param string $uid
     * @param int $bank_id
     * @param string $car_use_type
     * @return array
     * @return array all_series 所有车系
     * @throws
     */
    public function actionGetAllCarSeries1($uid, $bank_id, $car_use_type = 'cyc')
    {
        $s = $this->_getCarSMClassName($uid, $bank_id, $car_use_type, 's');
        $series = $s::find()->asArray()->all();
        $series_count = $s::find()->count();
        $r = [
            'all_series' => $series,
            'series_count' => $series_count,
        ];
        return $r;
    }

    /**
     * 根据车系id获取所有车型1
     * @param string $series_id 车系id 如果不是id，则通过名称寻找
     * @param string $uid
     * @param int $bank_id
     * @param string $car_use_type
     * @return array
     * @return array all_series 所有车系
     * @throws
     */
    public function actionGetAllCarModelsBySeriesId1($series_id, $uid, $bank_id, $car_use_type = 'cyc')
    {
        /*if (!is_numeric($series_id)){
            if (!$series_id){
                throw new ApiException(201906251156, "车系不能为空");
            }
            $s = $this->_getCarSMClassName($uid, $bank_id, $car_use_type, 's');
            $series = $s::findOne(['cs_car_text' => $series_id]);
            $series_id = $series->cs_id;
        }*/
        $where = ['series_id' => $series_id];
        $m = $this->_getCarSMClassName($uid, $bank_id, $car_use_type, 'm');
        $models = $m::find()->where($where)->asArray()->all();
        $models_count = $m::find()->where($where)->count();
        foreach ($models as $k => $v){
            if (!is_numeric($v['seat_number'])){
                $models[$k]['seat_number'] = 0;
            }
        }
        $r = [
            'all_models' => $models,
            'models_count' => $models_count,
        ];
        return $r;
    }

    /**
     * 根据o_id获取所有车辆识别信息
     * @desc get/post
     * @param string $o_id 贷前订单id
     * @throws
     * @return array
     * @return array list 车辆识别信息数据
     */
    public function actionGetAliCarInfo($o_id)
    {
        $list = AliCarinfoGetLog::find()->where(['o_id' => $o_id])->select(['vin', 'engine_number', 'car_color', 'registration_certificate_number', 'initial_registration_time', 'register_date', 'invoice_created_date', 'invoice_unit', 'invoice_number', 'plate_num', 'vehicle_type', 'car_model', 'owner', 'invoiceDataCode', 'invoiceNumber', 'billingTime', 'machineCode', 'result', 'o_id', 'uid', 'type', 'model', 'xhdwmc', 'request_djzs_str'])->asArray()->all();
        foreach ($list as $k => $v) {
            $list[$k]['type_name'] = AliCarinfoGetLog::getTypes()[$v['type']];
            if (!$list[$k]['car_model'])$list[$k]['car_model'] = $list[$k]['model'];
            if (!$list[$k]['invoice_unit'])$list[$k]['invoice_unit'] = $list[$k]['xhdwmc'];
            if (!$list[$k]['initial_registration_time']){
                $list[$k]['initial_registration_time'] = date("Y-m-d", strtotime($list[$k]['register_date']));
            }else{
                $list[$k]['initial_registration_time'] = date("Y-m-d", strtotime($list[$k]['initial_registration_time']));
            }
            if ($list[$k]['initial_registration_time'] == "1970-01-01"){
                $list[$k]['initial_registration_time'] = null;
            }
            if (!$list[$k]['registration_certificate_number'])$list[$k]['registration_certificate_number'] = $list[$k]['request_djzs_str'];
            if ($list[$k]['invoice_created_date']){
                $list[$k]['register_date'] = date("Y-m-d", strtotime($list[$k]['invoice_created_date']));
            }else{
                $list[$k]['register_date'] = null;
            }
            if ($list[$k]['register_date'] == "1970-01-01"){
                $list[$k]['register_date'] = null;
            }
        }
        return [
            'list' => $list,
        ];
    }

    /**
     * 计算评估参数验证接口
     * @desc get/post
     * @param int $bank_id 银行id
     * @param string $car_use_type 用车类型
     * @param string $car_pose 新旧类型
     * @param int $loan 贷款额
     * @param string $rate 公司费率
     * @param string $uid 用户id
     * @return array
     * @return bool result
     * @return string message
     */
    public function actionCarUseTypeLoanCheck($bank_id, $car_use_type = 'cyc', $car_pose, $loan, $rate, $uid)
    {
        if (!$car_use_type){
            $car_use_type = 'cyc';
        }
        $r = [
            'result' => 1,
            'message' => '',
        ];
        if ($car_use_type == 'syc'){
            $x = $this->actionCheckSyc($uid);
            if (!$x['result']){
                return $x;
            }
        }
        // 南京银行
        if ($bank_id == 11 || $bank_id == 17){
            if ($car_use_type == 'syc'){
                if ($car_pose == '新车'){
                    if ($loan <= 800000 && $loan >= 20000){
                        if ($rate <= 25.5){}else{
                            $r['result'] = 0;
                            $r['message'] = "公司费率必须小于等于25.5%";
                        }
                    }else{
                        $r['result'] = 0;
                        $r['message'] = "贷款额必须大于等于20000小于等于800000";
                    }
                }
            }
        }
        return $r;
    }

    /**
     * 判断能否使用商务车
     * @desc get/post绑定评估调用
     * @param string $uid 用户id
     * @return array
     * @return int result
     */
    public function actionCheckSyc($uid)
    {
        $r = [
            'result' => 1,
            'message' => '',
        ];
        $member = Member::find()->where(['u_id' => $uid])->one();
        if (!$member->branch){
            if ($member->dp && $member->dp->dp_id == 1){
                return $r;
            }else{
                $r['result'] = 0;
                $r['message'] = "不是网点用户没有权限操作商用车";
                return $r;
            }
        }
        if(!in_array('syc', Tools::str2arr($member->branch->br_car_use_type))){
            $r['result'] = 0;
            $r['message'] = "没有权限操作商用车";
            return $r;
        }
        return $r;
    }

    /**
     * 由vin获取车辆信息(che300基于VIN码获取车型)
     * @desc get/post
     * @param string $vin 车架号
     * @param string $series_id 车系id
     * @return mixed
     * @throws
     */
    public function actionGetCmodelByVin($vin, $series_id = null)
    {
        $vin = trim($vin);
        $cmb_count = Che300CmVinBind::find()->where(['vin' => $vin])->count();
        if ($cmb_count < 1){
            $url_pre = \common\components\che300\Config::$url_pre;
            $url = $url_pre . "/identifyModelByVIN";
            $params = [
                'vin' => $vin,
                'token' => \common\components\che300\Config::$token,
            ];
//           $_url = $url."?vin={$vin}&token=".Config::$token;
//           var_dump($_url);exit;
            $key = 'gcmbv--' . $vin;
//           \Yii::$app->cache->delete($key);
            $content = \Yii::$app->cache->get($key);
            if (!$content) {
                $client = new Client();
                Tools::log($vin, 'che300_get_cm_by_vin');
                $resp = $client->get($url, $params)->send();
                $content = $resp->content;
                \Yii::$app->cache->set($key, $content, 3600);
            }
            $arr = json_decode($content, true);
            $status = $arr['status'];
            if ($status == 0){
                throw new ApiException(201908201452, "vin获取车型失败:".$content);
            }
            $modelInfo = $arr['modelInfo'];
            $che300_car_model = new Che300CarModel();
            $cmb = new Che300CmVinBind();
            foreach ($modelInfo as $k => $v) {
                $m = Che300CarModel::findOne(['model_id' => $v['model_id']]);
                if (!$m){
                    $m = clone $che300_car_model;
                    $m->model_id = $v['model_id'];
                }
                $m->series_group_name = $v['series_group_name'];
                $m->color = $v['color'];
                $m->model_liter = $v['model_liter'];
                $m->model_year = (string)$v['model_year'];
                $m->brand_name = $v['brand_name'];
                $m->brand_id = $v['brand_id'];
                $m->series_id = $v['series_id'];
                $m->model_name = $v['model_name'];
                $m->model_price = $v['model_price'];
                $m->model_emission_standard = $v['model_emission_standard'];
                $m->model_gear = $v['model_gear'];
                $m->series_name = $v['series_name'];
                $m->min_reg_year = (string)$v['min_reg_year'];
                $m->max_reg_year = (string)$v['max_reg_year'];
                $m->ext_model_id = $v['ext_model_id'];
                if (!$m->save()) {
                    throw new ApiException(201908211007, "che300车型保存失败:".Model::getModelError($m));
                }
                $cm = clone $cmb;
                $cm->che300_model_id = $m->model_id;
                $cm->vin = $vin;
                if (!$cm->save()) {
                    throw new ApiException(201908211046, "che300车型绑定失败:".Model::getModelError($cm));
                }
            }
        }
        /*$cmbs = Che300CmVinBind::find()->where(['vin' => $vin])->groupBy(['series_id'])->all();
        $cms = [];
        foreach ($cmbs as $k => $v){
            $cms[] = $v->che300Model->toArray();
        }*/
        $bind_tn = Che300CmVinBind::tableName();
        $c3cm_tn = Che300CarModel::tableName();
        $sql = <<<SQL
SELECT {$bind_tn}.vin AS vin, {$c3cm_tn}.* FROM {$bind_tn} LEFT JOIN {$c3cm_tn} ON {$bind_tn}.che300_model_id =  {$c3cm_tn}.model_id WHERE vin = '{$vin}' 
SQL;
        if ($series_id){
            $series_id = trim($series_id);
            $sql = <<<SQL
{$sql} AND {$c3cm_tn}.series_id = {$series_id}
SQL;
        }else{
            $sql = <<<SQL
{$sql} GROUP BY {$c3cm_tn}.series_id
SQL;
        }
        $cms = \Yii::$app->db->createCommand($sql)->queryAll();
        foreach ($cms as $k => $v) {
            $cms[$k]['cs_car_type'] = '';
            $cms[$k]['seat_number'] = 0;
            $cs_m = SlCarModel::findOne(['model_id' => $v['model_id']]);
            $cs_s = $cs_m->slCarSeries;
            if ($cs_s) {
                $cms[$k]['cs_car_type'] = $cs_s->cs_car_type;
                $cms[$k]['seat_number'] = $cs_m->seat_number;
            }
        }
        $r = [
            'all' => $cms,
        ];
        return $r;
    }

    /**
     * (che300返回VIN选定车型)
     * @desc get/post
     * @param string $vin
     * @param string $modelId
     * @return mixed
     * @throws
     */
    public function actionCmodelBindVin($vin, $modelId)
    {
        $vin = trim($vin);
        $url_pre = \common\components\che300\Config::$url_pre;
        $url = $url_pre . "/common/eval";
        $params = [
            'vin' => $vin,
            'token' => \common\components\che300\Config::$token,
            'modelId' => $modelId,
            'oper' => "notifyVINResult",
        ];
        $client = new Client();
        $resp = $client->get($url, $params)->send();
        $content = $resp->content;
        $arr = json_decode($content, true);
        $status = $arr['status'];
        if ($status == 0){
            throw new ApiException(201908201518, "绑定失败:".$content);
        }
        $r = $arr;
        return $r;
    }
}